package router

import (
	"fmt"
	"goGin/model"

	"github.com/garyburd/redigo/redis"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Demo(r *gin.Engine, db *gorm.DB, d redis.Conn) {
	r.GET("/adddata", func(c *gin.Context) { //创建记录
		data := &model.User{
			Username: "12dsdasd",
		}
		state := 200
		msg := "添加成功"
		if result := db.Create(data); result.Error != nil {
			state = 400
			msg = "数据写入错误"
		}
		c.JSON(200, gin.H{
			"state": state,
			"msg":   msg,
		})
	})
	r.GET("/getdata", func(c *gin.Context) { //查询记录
		models := []model.User{}
		var count int64
		state := 200
		msg := "查询成功"
		result := db.Limit(3).Where("").Find(&models)
		if result.Error != nil {
			state = 400
			msg = "查询错误"
			models = []model.User{}
		} else {
			result.Count(&count)
		}
		c.JSON(200, gin.H{
			"state": state,
			"msg":   msg,
			"count": count,
			"data1": models,
		})
	})

	r.POST("/getdata", func(c *gin.Context) { //查询记录
		var Json model.Query
		if err := c.ShouldBindJSON(&Json); err != nil {
			fmt.Print(err.Error())
		}
		// model.Dbquery(json, "AND")
		fmt.Print(Json)
		models := []model.User{}
		var count int64
		state := 200
		msg := "查询成功"
		query := Json.Query
		for k, v := range query {
			fmt.Print(k, v)
			if v == "" || v == nil {
				delete(query, k)
			}
		}
		fmt.Print(query)
		result := db.Limit(3).Where(query).Find(&models)
		if result.Error != nil {
			state = 400
			msg = "查询错误"
			models = []model.User{}
		} else {
			result.Count(&count)
		}
		c.JSON(200, gin.H{
			"state": state,
			"msg":   msg,
			"data":  models,
		})
	})
}
